package com.lc.recovery.ui.activity.warehousehome;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.base.BaseDialog;
import com.lc.recovery.R;
import com.lc.recovery.app.AppActivity;
import com.lc.recovery.bean.AddShopBean;
import com.lc.recovery.bean.RecoveryBean;
import com.lc.recovery.http.request.ShopsApi;
import com.lc.recovery.http.request.ShopsNumsApi;
import com.lc.recovery.http.request.StorageCountsApi;
import com.lc.recovery.http.request.StorageOutApi;
import com.lc.recovery.http.request.StoragerNameApi;
import com.lc.recovery.http.response.PublicMsg;
import com.lc.recovery.http.response.ShopsBean;
import com.lc.recovery.http.response.ShopsNumsBean;
import com.lc.recovery.http.response.StorageCountsBean;
import com.lc.recovery.http.response.StorageTotalsBean;
import com.lc.recovery.http.response.StoragerNameBean;
import com.lc.recovery.other.IntentKey;
import com.lc.recovery.ui.dialog.MessageDialog;
import com.lc.recovery.util.BigDecimalUtils;
import com.lc.recovery.util.SPUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OutboundGoodsActivity extends AppActivity implements TextView.OnEditorActionListener {
    @BindView(R.id.rv_businessshop)
    RecyclerView rvBusinessshop;

    @BindView(R.id.et_weight)
    EditText etWeight;
    @BindView(R.id.tv_recovery_name)
    TextView tvRecoveryName;


    @BindView(R.id.img_erwuma)
    ImageView imgErwuma;
    @BindView(R.id.tv_ruku)
    TextView tvRuku;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedscrollview;
    @BindView(R.id.ll_shops)
    LinearLayout llShops;
    @BindView(R.id.rv_weight)
    RecyclerView rvWeight;
    @BindView(R.id.tv_shopprice)
    TextView tvShopprice;
    @BindView(R.id.tv_totoalprice)
    TextView tvTotoalprice;
    @BindView(R.id.rv_select_weight)
    RecyclerView rvSelectWeight;
    @BindView(R.id.tv_kg)
    TextView tvKg;
    private String pid;
    private List<ShopsBean.DataBean> shopdata=new ArrayList<>();
    private String priceId;
    private List<String> shopdatatitle = new ArrayList<>();
    private List<StorageTotalsBean.DataBean> datas;
    private int pos;
    private BaseQuickAdapter<StorageTotalsBean.DataBean, BaseViewHolder> goodsdapter;
    private BaseQuickAdapter<AddShopBean, BaseViewHolder> addadapter;
    private List<AddShopBean> addShopList = new ArrayList<>();
    List<RecoveryBean> recoveryArray=new ArrayList<>();

    private BaseQuickAdapter<ShopsBean.DataBean, BaseViewHolder> weightdapter;
    private String title;
    private final int SCANNIN_GREQUEST_CODE = 107;//扫描二维码
    @Override
    protected int getLayoutId() {
        return R.layout.activity_outboundgoods;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        pid = getIntent().getStringExtra("id");
        datas = (List<StorageTotalsBean.DataBean>) getIntent().getSerializableExtra("datas");
        storager_name();
        shops(pid);

        //        分类列表
        for (int i = 0; i < datas.size(); i++) {
            if (String.valueOf(datas.get(i).getId()).equals(pid)) {
                datas.get(i).setIsgrop(true);
                pos = i;
            } else {
                datas.get(i).setIsgrop(false);
            }
        }

        goodsdapter = new BaseQuickAdapter<StorageTotalsBean.DataBean, BaseViewHolder>
                (R.layout.item_recovery_shopnew, datas) {

            @Override
            protected void convert(BaseViewHolder baseViewHolder, StorageTotalsBean.DataBean dataBean) {
                baseViewHolder.setText(R.id.tv_name, dataBean.getShops());
                if (dataBean.isIsgrop()) {
                    baseViewHolder.setBackgroundResource(R.id.ll_bg, R.color.color01B467);

                } else {
                    baseViewHolder.setBackgroundResource(R.id.ll_bg, R.color.colorf5f5f5);
                }

            }
        };

        goodsdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {

                for (StorageTotalsBean.DataBean bean : datas) {
                    bean.setIsgrop(false);
                }
                StorageTotalsBean.DataBean bean = datas.get(position);
                bean.setIsgrop(!bean.isIsgrop());
                goodsdapter.notifyDataSetChanged();
                shops(datas.get(position).getId() + "");

                etWeight.setText("");
                etWeight.setHint("输入重量");

                tvTotoalprice.setText("");
                tvShopprice.setText("输入价格");
            }
        });
        rvBusinessshop.smoothScrollToPosition(pos);
        rvBusinessshop.setAdapter(goodsdapter);

//        添加的商品列表
                addadapter = new BaseQuickAdapter<AddShopBean, BaseViewHolder>(R.layout.item_select_weight, addShopList) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, AddShopBean bean) {
                baseViewHolder.setText(R.id.tv_name, bean.getTitle());
                baseViewHolder.setText(R.id.tv_weight, bean.getWeigth() + "公斤");
                baseViewHolder.setText(R.id.tv_price, bean.getPrice());
                baseViewHolder.getView(R.id.rl_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 消息对话框
                        new MessageDialog.Builder(getActivity())
                                // 标题可以不用填写
                                .setTitle("提示")
                                // 内容必须要填写
                                .setMessage("是否要删除此条数据")
                                // 确定按钮文本
                                .setConfirm(getString(R.string.common_confirm))
                                // 设置 null 表示不显示取消按钮
                                .setCancel(getString(R.string.common_cancel))
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setListener(new MessageDialog.OnListener() {

                                    @Override
                                    public void onConfirm(BaseDialog dialog) {

                                        addShopList.remove(baseViewHolder.getPosition());
                                        recoveryArray.remove(baseViewHolder.getPosition());
                                        addadapter.notifyDataSetChanged();
                                        ontotalPrice(addShopList);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {

                                    }
                                })
                                .show();

                    }
                });
            }
        };
        rvSelectWeight.setAdapter(addadapter);
//        二级分类
        weightdapter = new BaseQuickAdapter<ShopsBean.DataBean, BaseViewHolder>(R.layout.item_recovery_shopweight, shopdata) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, ShopsBean.DataBean bean) {
                baseViewHolder.setText(R.id.tv_name, bean.getTitle());
                baseViewHolder.setText(R.id.tv_price, bean.getPrice());

                if (bean.isIsgrop()) {
                    baseViewHolder.setImageResource(R.id.iv_iv, R.mipmap.icon_shop_pay_select);

                } else {
                    baseViewHolder.setImageResource(R.id.iv_iv, R.mipmap.icon_shop_pay);
                }
            }
        };
        weightdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                for (ShopsBean.DataBean bean : shopdata) {
                    bean.setIsgrop(false);
                }
                ShopsBean.DataBean bean = shopdata.get(position);
                bean.setIsgrop(!bean.isIsgrop());
                priceId = shopdata.get(position).getId() + "";
                title = shopdata.get(position).getTitle();
                weightdapter.notifyDataSetChanged();
                etWeight.setText("");
                etWeight.setHint("输入重量");
                tvTotoalprice.setText("");
                shops_nums(priceId);
                tvShopprice.setText(shopdata.get(position).getPrice() + "");
            }
        });
        rvWeight.setAdapter(weightdapter);
        etWeight.setOnEditorActionListener(this);
    }

    private void shops(String id) {
        EasyHttp.post(this)
                .api(new ShopsApi().setPid(id)).request(new HttpCallback<ShopsBean>(this) {

            @Override
            public void onSucceed(ShopsBean data) {
                if (data.getCode() == 200) {
                    shopdata.clear();
                    shopdata.addAll(data.getData());
                    weightdapter.setNewData(shopdata);
                    weightdapter.notifyDataSetChanged();
                } else {
                    toast(data.getMsg());

                }


            }


            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    /**
     * 二级品类库存查询
     *
     * @param id
     */
    private void shops_nums(String id) {
        EasyHttp.post(this)
                .api(new ShopsNumsApi().setId(id)).request(new HttpCallback<ShopsNumsBean>(this) {

            @Override
            public void onSucceed(ShopsNumsBean data) {
                if (data.getCode() == 200) {
                    tvKg.setText(data.getNums()+"kg");
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void storager_name() {
        EasyHttp.post(this)
                .api(new StoragerNameApi().setUser_id(SPUtil.get(getContext(), IntentKey.USERID, ""))).request(new HttpCallback<StoragerNameBean>(this) {

            @Override
            public void onSucceed(StoragerNameBean data) {
                if (data.getCode() == 200) {
                    tvRecoveryName.setText(data.getName());
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void storage_out() {
        if (recoveryArray.size()==0){
            toast("请添加类目");
        }
        if (etWeight.getText().toString().trim().isEmpty()) {
            toast("请填写出库重量");
            return;
        }
        EasyHttp.post(this)
                .api(new StorageOutApi().setStorager_id(SPUtil.get(getContext(), IntentKey.USERID, "")).setShops(recoveryArray)).request(new HttpCallback<PublicMsg>(this) {

            @Override
            public void onSucceed(PublicMsg data) {
                if (data.getCode() == 200) {
                    toast(data.getMsg());
                    finish();
                } else {
                    toast(data.getMsg());
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private void ontotalPrice(List<AddShopBean> list) {
        if (list.size()==0){

        }
        double price=0;
        for (int i = 0; i <list.size() ; i++) {
            price+=Double.parseDouble(list.get(i).getPrice().replace("元",""));
        }
//        tvPrice.setText(price+"元");
    }
    @OnClick({R.id.tv_ruku, R.id.tv_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_ruku:
                storage_out();
                break;
            case R.id.tv_add:
                order_price(priceId);

                break;

        }
    }

    private void order_priceed(String priceId) {
        if (etWeight.getText().toString().isEmpty()) {
            toast("请输入入库重量");
            return;
        }
        EasyHttp.post(this)
                .api(new StorageCountsApi().setShops_id(priceId).setWorker_id(SPUtil.get(this, IntentKey.USERID, "")).setWeights(BigDecimalUtils.div(etWeight.getText().toString(), "1", 2))).request(new HttpCallback<StorageCountsBean>(this) {

            @Override
            public void onSucceed(StorageCountsBean data) {
                if (data.getCode() == 200) {
                    tvTotoalprice.setText(data.getReal_amount() + "元");
                } else {
                    toast(data.getMsg());
                }
            }
        });

    }
    private void order_price(String pid) {
        if (etWeight.getText().toString().isEmpty()) {
            toast("请输入入库重量");
            return;
        }
        EasyHttp.post(this)
                .api(new StorageCountsApi().setShops_id(pid).setWorker_id(SPUtil.get(this, IntentKey.USERID, "")).setWeights(BigDecimalUtils.div(etWeight.getText().toString(), "1", 2))).request(new HttpCallback<StorageCountsBean>(this) {

            @Override
            public void onSucceed(StorageCountsBean data) {
                if (data.getCode() == 200) {
                    tvTotoalprice.setText(data.getReal_amount() + "元");
                    if (etWeight.getText().toString().trim().isEmpty()){
                        toast("请输入回收商品重量");
                        return;
                    }
                    if (tvTotoalprice.getText().toString().trim().isEmpty()){
                        toast("请选择称重类目");
                        return;
                    }
                    AddShopBean addShopBean=new AddShopBean();
                    addShopBean.setId(priceId);
                    addShopBean.setTitle(title);
                    addShopBean.setWeigth(etWeight.getText().toString().trim());
                    addShopBean.setPrice(tvTotoalprice.getText().toString().trim());
                    addShopList.add(addShopBean);
                    addadapter.setNewData(addShopList);
                    ontotalPrice(addShopList);
                    addadapter.notifyDataSetChanged();
                    RecoveryBean recoveryBean=new RecoveryBean();
                    recoveryBean.setShops_id(addShopBean.getId());
                    recoveryBean.setWeights(addShopBean.getWeigth());

                    recoveryArray.add(recoveryBean);
                } else {
                    toast(data.getMsg());

                }


            }


            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
        if (event != null && event.getAction() != KeyEvent.ACTION_DOWN) {
            return false;
        }
        if (actionId == EditorInfo.IME_ACTION_DONE
                || event == null
                || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            order_priceed(priceId);
        }

        return false;
    }


}
